﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using LKVMLMLib;
using System.Reflection;
using System.Web;
using System.ServiceModel.Channels;

namespace LKVService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "OrderService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select OrderService.svc or OrderService.svc.cs at the Solution Explorer and start debugging.
    public class OrderService 
    {

        public string GetData(int value)
        {
            return string.Format("-- : {0}", value);
        }

        public Order[] getListOrder()
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var rt = db.Orders.ToArray();
                return rt;
            }
        }

        /**
         * @summary Lay danh sach Package tu userid
         * @param name="userId"
         */         
        public ManagerPack[] getListPackageByUserId(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                //var rt = db.Orders.Where(w=>w.UserId==userId).ToArray();
                var rt = db.Orders.Where(w => w.UserId == userId)
                    .Select(s => new ManagerPack(){
                        Id = s.ID, Percent = s.Percent, Title = s.ID_Order
                    })
                    .ToArray();
                return rt;
            }
        }

        public Tuple<int,CustomOrder[]> getListOrderWithCondition(string searchType, string searchtext,int status, DateTime fromdate, DateTime todate,int fromPage = 0, int toPage = 100)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                todate = todate.AddHours(23);
                var sql = from U in db.UserProfiles
                          join O in db.Orders.Where(w => w.Date.Value >= fromdate && w.Date.Value <= todate)
                          on U.UserId equals O.UserId
                          join P in db.Packages
                          on O.Package_id equals P.ID into ps
                          from L in ps.DefaultIfEmpty()
                          select new CustomOrder
                            {
                                ID = O.ID,
                                STT = U.UserName,
                                ID_OrDer = O.ID_Order,
                                HoTen = U.HOTEN,
                                Amount = O.numpackage != null ? O.Amount * O.numpackage : O.Amount ,
                                PV = O.Pv,
                                CreateDate = O.Date,
                                Package_Name = L.PackageName,
                                Numpackage = O.numpackage,
                                NewAction = O.Action
                            };
                if (searchType == "Username")
                {
                    sql = sql.Where(w => w.STT.Contains(searchtext));
                }
                else if (searchType == "Mã Đơn hàng")
                {
                    sql = sql.Where(w => w.ID_OrDer.Contains(searchtext));

                }
                if (status == 1)
                    sql = sql.Where(x => x.NewAction == true);
                else if (status == 2)
                    sql = sql.Where(x => x.NewAction == false);
                int totalItems = sql.Count();
                if (fromPage == 0 || fromPage == 1)
                {
                    return new Tuple<int, CustomOrder[]>(totalItems, sql.OrderByDescending(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                }
                else
                    return new Tuple<int, CustomOrder[]>(totalItems, sql.OrderByDescending(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());

            }
        }
        public Order FindOrderbyId(int id)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Orders.Where(w => w.ID == id).FirstOrDefault();
            }
        }
        public Order findOrderbyIDOrder(string ID_Order)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var order =  db.Orders.Where(w => w.ID_Order != null && w.ID_Order.Equals(ID_Order)).FirstOrDefault();
                return order;
            }
        }
        public Order[] getListOrderByUserId(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Orders.Where(w => w.UserId == userId).ToArray();
            }       
        }
        // package
        public Package[] getListPackage()
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var rt = db.Packages.ToArray();
                return rt;
            }
        }  
        public Package findPackagebyPackageByName(string name)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Packages.Where(w => w.PackageName == name).FirstOrDefault();
            }
        }
        public Package findPackagebyPackageByPrice(double price)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Packages.Where(w => w.Price == price).FirstOrDefault();
            }
        }
        public Package findPackagebyPackageById(int pkId)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.Packages.Where(w => w.ID == pkId).FirstOrDefault();
            }
        }
        public int AddPackage(Package c)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Packages.Add(c);
                db.SaveChanges();
                _Return = 1;
            }

            return _Return;
        }
        public int RemovePackage(int id)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var removePackage = db.Packages.Where(w => w.ID == id).FirstOrDefault();
                db.Packages.Remove(removePackage);
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }
        public int EditPackage(LKVMLMLib.Package c)
        {
            int _Return = 0;
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var EditPackage = db.Packages.Where(w => w.ID == c.ID).FirstOrDefault();
                EditPackage.PackageName = c.PackageName;
                EditPackage.PackageCode = c.PackageCode;
                EditPackage.Price = c.Price;
                EditPackage.PV=c.PV;
                db.SaveChanges();
                _Return = 1;
            }
            return _Return;
        }   
        // Order 
        public int RemoveOrder (int id)
        {
            int _rt = 0;
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var RemoveOrder = db.Orders.Where(w => w.ID == id).FirstOrDefault();
                db.Orders.Remove(RemoveOrder);
                db.SaveChanges();
                _rt = 1;
            }
            return _rt;
        }
        public void caculateCommisstion(int user_id, double amount, int? pv, int? OrderID, DateTime? Date)
        {
            object[] parameters = { user_id, amount, pv, OrderID, Date };
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var staticdb = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var plugins = staticdb.CommissionConfigs.Where(t => (t.Status == true));
                foreach (var plugin in plugins.ToList())
                {

                    string plugin_name = plugin.CommissionName + ".ExecuteCommission";
                    try
                    {
                        var instance = System.Activator.CreateInstance(Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service"));
                        var class_name = Type.GetType(plugin_name + ", " + plugin.CommissionName.Substring(7) + "Service");
                        var method = class_name.GetMethod("executeDirectly");
                        method.Invoke(instance, parameters);

                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
            }
        }
        public bool addOrder(int order_id, int user_id, float amount, int selectedPakageID, string ID_Order, DateTime CreateDate, bool status, bool isFirst, int numpackage, int Percent = 0, string description = "", int achievement = 0, bool enterRoom=false)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var us = new LKVService.User();
                if(amount ==0) return false;
                var User = db.UserProfiles.Where(w => w.UserId == user_id).ToList().FirstOrDefault();
                var Order = db.Orders.Where(w => w.ID == order_id).ToList().FirstOrDefault();                
                try
                {
                    if (User == null) return false;                    
                    if (Order ==null)
                    {
                        Order newOrder = new Order();
                        newOrder.UserId = User.UserId;
                        newOrder.Amount = amount;
                        newOrder.ID_Order = ID_Order;
                        newOrder.Date = CreateDate;
                        newOrder.Action = status;
                        newOrder.IsFirst = isFirst;
                        newOrder.numpackage = numpackage;
                        newOrder.Percent = Percent;
                        newOrder.Description = description;
                        newOrder.Achievement = achievement;
                        newOrder.EnterRoom = enterRoom;
                        db.Orders.Add(newOrder);
                        if (status)
                            User.Status = true;
                        db.SaveChanges();
                        if (status)
                        {
                            caculateCommisstion((int)newOrder.UserId, (double)newOrder.Amount, newOrder.Pv, newOrder.ID, newOrder.Date);
                        }
                        return true; 
                    }
                    else
                    {
                        // edit
                        var gr = db.Orders.Where(w => w.ID == order_id).ToList().FirstOrDefault();
                        if (gr == null) throw new Exception("Orders Không Tồn Tại");
                        gr.Date = CreateDate;
                        gr.ID_Order = ID_Order;                            
                        db.SaveChanges();
                        return true;
                    }
                }                                    
                catch (Exception ex)
                {
                    return false;
                }
            }
            
        }
        public bool addOrder2(int order_id, int user_id, float amount, int selectedPakageID, string ID_Order, DateTime CreateDate, bool status, bool isFirst, int numpackage, string _description = "", int achievement = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                if (amount == 0) return false;
                var User = db.UserProfiles.Where(w => w.UserId == user_id).ToList().FirstOrDefault();
                var Order = db.Orders.Where(w => w.ID == order_id).ToList().FirstOrDefault();
                var exchange = db.ExchangeConfigs.Where(w => w.Name == "IN").Select(s => s.Value).SingleOrDefault();
                try
                {
                    if (User == null) return false;
                    if (Order == null)
                    {
                        // add new                       
                        var _package = db.Packages.Where(w => w.ID == selectedPakageID).SingleOrDefault();
                        Order newOrder = new Order();
                        newOrder.UserId = User.UserId;
                        newOrder.Amount = amount;
                        newOrder.ID_Order = ID_Order;
                        newOrder.Date = CreateDate;
                        newOrder.Action = status;
                        newOrder.IsFirst = isFirst;
                        newOrder.numpackage = numpackage;
                        newOrder.Description = _description;
                        newOrder.Achievement = achievement;
                        if (_package != null)
                        {
                            User.PackageID = _package.ID;
                            newOrder.Package_id = _package.ID;
                            newOrder.Pv = _package.PV;
                        }

                        else
                        {
                            newOrder.Pv = Convert.ToInt32(newOrder.Amount / exchange);
                        }
                        db.Orders.Add(newOrder);
                        if (isFirst && status)
                            User.Status = true;
                        db.SaveChanges();
                        if (status)
                        {
                            caculateCommisstion((int)newOrder.UserId, (double)newOrder.Amount, newOrder.Pv, newOrder.ID, newOrder.Date);
                        }
                        return true;
                    }
                    else
                    {
                        // edit
                        var gr = db.Orders.Where(w => w.ID == order_id).ToList().FirstOrDefault();
                        if (gr == null) throw new Exception("Orders Không Tồn Tại");
                        gr.Date = CreateDate;
                        gr.ID_Order = ID_Order;
                        db.SaveChanges();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }
        
        public void DeleteOders(List<int?> del_ids)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                db.Orders.RemoveRange(db.Orders.Where(w => del_ids.Contains(w.ID)));

                db.Profits.RemoveRange(db.Profits.Where(w => del_ids.Contains(w.OrderID)));
                db.SaveChanges();
            }
            
        }
        public Order getOrder(int ID)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.Orders.Where(w => w.ID == ID).ToList().FirstOrDefault();
            }            
        }
        public int UpdateOrder (Order c)
        {
            int _rt = 0;
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var Update = db.Orders.Where(w => w.ID == c.ID).SingleOrDefault();
                Update.ID_Order = c.ID_Order;
                Update.IsFirst = c.IsFirst;
                Update.Package_id = c.Package_id;
                Update.Pv = c.Pv;
                Update.UserId = c.UserId;
                Update.Action = c.Action;
                Update.Date = c.Date;
                Update.Amount = c.Amount;
                Update.EnterRoom = c.EnterRoom;
                db.SaveChanges();
                _rt = 1;
            }
            return _rt;
        }
        public bool activeOrder(int orderid)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var us = new LKVService.User();
                var idOrder = db.Orders.Where(w => w.ID == orderid).ToList().FirstOrDefault();
                idOrder.Action = true;
                var edituser = db.UserProfiles.Where(w => w.UserId == idOrder.UserId).SingleOrDefault();
                if (edituser != null)
                {
                    edituser.Status = true;
                    
                }
                db.SaveChanges();
                // Tường thêm: xét Level cho User
                us.updateUserLevelAfterAddOrder(edituser.UserId);
                this.caculateCommisstion((int)idOrder.UserId, (double)idOrder.Amount,idOrder.Pv != null ? (int)idOrder.Pv : 0, idOrder.ID, idOrder.Date);
                return true;
            }
            
        }
        public OrderViewModel[] Ordermonth(DateTime? Date, int userid)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                int it = 0;
                var _orderMonth = db.UserProfiles.Join(db.Orders.Where(o => o.Date.Value.Year == Date.Value.Year && o.Date.Value.Month == Date.Value.Month),
                          p => p.UserId,
                          c => c.UserId, (p, c) => new { user = p, order = c }).Select(x => new OrderViewModel
                          {
                              UserId = x.user.UserId,
                              UserName = x.user.UserName,
                              HoTen = x.user.HOTEN,
                              Amount = (x.order != null ? x.order.Amount : 0),
                              Date = (x.order != null ? x.order.Date : new DateTime(0001, 01, 01)),
                              OrderId = (x.order != null ? x.order.ID_Order : "--")
                          });
                var lsF1 = db.UserProfiles.Where(x => x.Parent_ID == userid).ToList();
                var _model = new List<OrderViewModel>();
                foreach (var ob in lsF1)
                {
                    foreach (var obj in _orderMonth)
                    {
                        if (ob.UserId == obj.UserId)
                        {
                            it++;
                            _model.Add(new OrderViewModel
                            {
                                UserId = ob.UserId,
                                Amount = obj.Amount,
                                Date = obj.Date,
                                OrderId = obj.OrderId,
                                HoTen = obj.HoTen,
                                UserName = obj.UserName,
                                Stt = it
                            });
                        }
                    }
                }
                return _model.ToArray();
            }

        }
        public OrderViewModel[] SaleperSonal(DateTime? Date, int userid)
        {
            string connection = DuAnDaCapEntities.getDomain(); 
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                int it = 0;
                var orderMonth = db.Orders.Join(db.UserProfiles, c => c.UserId, p => p.UserId, (c, p) => new { c.UserId, p.UserName, p.HOTEN, c.Amount, c.Date, c.ID_Order })
                     .Where(o => o.Date.Value.Year == Date.Value.Year && o.Date.Value.Month == Date.Value.Month);

                var model = new List<OrderViewModel>();
                foreach (var obj in orderMonth)
                {
                    if (obj.UserId == userid)
                    {
                        it++;
                        model.Add(new OrderViewModel
                        {
                            UserId = Convert.ToInt32(obj.UserId),
                            Amount = obj.Amount,
                            Date = obj.Date,
                            OrderId = obj.ID_Order,
                            HoTen = obj.HOTEN,
                            UserName = obj.UserName,
                            Stt = it
                        });
                    }
                }
                return model.ToArray();
            }
        }

        public GConfig GetGConfig()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.GConfigs.SingleOrDefault();
            }
        }
        public  List<GConfig> GetListGconfig()
        {
           string connection = DuAnDaCapEntities.getDomain();
           using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
           {
               return db.GConfigs.ToList();
           }
        }
        public bool UpdateGconfig(GConfig ud)
        {
            bool result = false;
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var chooseGcf = db.GConfigs.Where(w => w.Id == ud.Id).SingleOrDefault();
                chooseGcf.isMaintainent = ud.isMaintainent;
                chooseGcf.PenddingWallet = ud.PenddingWallet;
                chooseGcf.ROI = ud.ROI;
                db.SaveChanges();
                result = true;
                return result;
            }
        }

        public double ProfitForDate(int UserId, DateTime DateCreate)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var result = db.Profits.Where(w => w.UserId == UserId && w.CreateDate.Value == DateCreate.Date).Sum(s => s.Amount);                 
                if (result!=null)
                {
                    return result.Value;
                }
                return 0.00;
            }
        }
        public double GetOrderByUserID(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var result = db.Orders.Where(w => w.UserId == UserId).Sum(s => s.Amount);
                if (result != null)
                {
                    return result.Value;
                }
                return 0;
            }
        }
        public List<HistoryProfitPackDetail> getProfitsByOrder(int OrderId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var result = db.Profits.Where(w => w.OrderID == OrderId)
                    .Where(w => w.ProfitType == "HoaHongSponsorPack" || w.ProfitType == "HoaHongPackLine" || w.ProfitType == "HoaHongDailyPay")
                    .OrderByDescending(o=>o.CreateDate)
                    .AsEnumerable()
                    .Select(s => new HistoryProfitPackDetail() {
                        Date = s.CreateDate.Value.ToString("MM/dd/yyyy"),
                        Profit = s.Amount.Value.ToString("0.00"),
                    })
                    .ToList();
                return result;
            }
        }
        public ProvideOrderView[] getListProvideOrderByOrderId(int orderId = 0)
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.ProvideOrders.Where(w => w.OrderId == orderId).Select(s => new ProvideOrderView
                {
                    Id = s.Id,
                    UserIdGive = s.UserIdGive.Value,
                    UserGive = db.UserProfiles.Where(w=>w.UserId == s.UserIdGive.Value).FirstOrDefault().UserName,
                    UserIdGet = s.UserIdGet.Value,
                    UserGet = db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault().UserName,
                    OrderId = s.OrderId.Value,
                    Id_Order =db.Orders.Where(w=>w.ID == s.OrderId.Value).FirstOrDefault().ID_Order,
                    Amount = s.Amount == null ? 0 : s.Amount.Value,
                    Status = s.Status.Value,
                    RoomCode = s.RoomCode,
                    PhoneGet = db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault() != null ?
                    db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault().SDTNHARIENG : null,
                    EmailGet = db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault() != null ?
                    db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault().EMAIL : null
                }).ToArray();
            }
        }

        public List<PH> getListProvideHelpByUserId(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.PHs.Where(w => w.UserId == userId).ToList();
            }
        }
        public RoomCode[] getListRoomCodeByUserRecieve(int userRecieve = 0)
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var lst = db.RoomCodes.Join(db.ReviveRooms.Where(w=>w.UserId == userRecieve),c=>c.RoomCode1,p=>p.RoomCode,(c,p)=>new{room = c,recieve = p}).Select(s=>s.room).ToArray();
                return lst;
            }       
        }
        public ProvideOrderView[] getListProvideOrderByUserRecieve(string roomCode = "", int userRecieveId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.ProvideOrders.Where(w => w.RoomCode.Equals(roomCode) && w.UserIdGet == userRecieveId).Select(s => new ProvideOrderView
                {
                    Id = s.Id,
                    UserIdGive = s.UserIdGive.Value,
                    UserGive = db.UserProfiles.Where(w => w.UserId == s.UserIdGive.Value).FirstOrDefault().UserName,
                    UserIdGet = s.UserIdGet.Value,
                    UserGet = db.UserProfiles.Where(w => w.UserId == s.UserIdGet.Value).FirstOrDefault().UserName,
                    OrderId = s.OrderId.Value,
                    Id_Order = db.Orders.Where(w => w.ID == s.OrderId.Value).FirstOrDefault().ID_Order,
                    Amount = s.Amount == null ? 0 : s.Amount.Value,
                    Status = s.Status.Value,
                    RoomCode = s.RoomCode
                }).ToArray();
            }
        }
        public ProvideOrderView findProvideOrderById(int provideOrderId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                var pod = db.ProvideOrders.Where(w => w.Id == provideOrderId).FirstOrDefault();
                var podv = new ProvideOrderView();
                if (pod != null)
                {
                    podv.Id = pod.Id;
                    podv.Amount = pod.Amount != null ? pod.Amount.Value : 0;
                    podv.Id_Order = db.Orders.Where(w=>w.ID == pod.OrderId).FirstOrDefault() != null ? db.Orders.Where(w=>w.ID == pod.OrderId).FirstOrDefault().ID_Order : null;
                    podv.OrderId = pod.OrderId.Value;
                    podv.Status = pod.Status.Value;
                    podv.UserGet = db.UserProfiles.Where(w => w.UserId == pod.UserIdGet.Value).FirstOrDefault().UserName;
                    podv.UserIdGet = pod.UserIdGet.Value;
                    podv.UserGive = db.UserProfiles.Where(w => w.UserId == pod.UserIdGive.Value).FirstOrDefault().UserName;
                    podv.UserIdGive = pod.UserIdGive.Value;
                    return podv;
                }
                else
                    return null;
            }           
        }
        public bool updateStatusProvideOrder(int provideOrderId = 0, int Status = 0)
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    var pod = db.ProvideOrders.Where(w => w.Id == provideOrderId).FirstOrDefault();
                    if (pod == null)
                        return false;
                    pod.Status = Status;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        public bool checkActiveOrderByAllProvideOrder(int provideOrderId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    var pod = db.ProvideOrders.Where(w => w.Id == provideOrderId).FirstOrDefault();
                    if (pod == null)
                        return false;
                    var lstProvideOrder = db.ProvideOrders.Where(w => w.OrderId == pod.OrderId).ToList();
                    if (lstProvideOrder.Count == 0)
                        return false;
                    var check = lstProvideOrder.Where(w => w.Status == 0 || w.Status == 1).ToList();
                    if (check.Count == 0)
                        return true;
                    else
                        return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        public bool addWaitingProvideRoom(int userId = 0, int orderId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.WaitingProvideRooms.Add(new WaitingProvideRoom
                    {
                        CreateDate = DateTime.Now,
                        OrderId = orderId,
                        UserId = userId
                    });
                    db.SaveChanges();
                   return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            } 
        }
        public bool addWaitingReceivedRoom(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try
                {
                    db.WaitingReceivedRooms.Add(new WaitingReceivedRoom
                    {
                        CreateDate = DateTime.Now,
                        UserId = userId,
                        Action = false
                    });
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        public RoomCode findRoomCodeByCode(string roomCode = "")
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.RoomCodes.Where(w => w.RoomCode1.Equals(roomCode)).FirstOrDefault();
            }
        }
        public bool checkUpdateStatusRoomCode(int roomId = 0)
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                try 
                {
                    var room = db.RoomCodes.Where(w => w.Id == roomId).FirstOrDefault();
                    if (room != null)
                    {
                        var lstProvideOrder = db.ProvideOrders.Where(w => w.RoomCode.Equals(room.RoomCode1)).ToList();
                        if (lstProvideOrder.Count > 0)
                        {
                            var check = lstProvideOrder.Where(w => w.Status == 0 || w.Status == 1).ToList();
                            if (check.Count == 0)
                            {
                                room.Status = true;
                                db.SaveChanges();
                                return true;
                            }
                            else
                                return false;
                        }
                        else
                            return false;
                    }
                    else
                        return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        public string findLevelNameByLevelCode(string levelCode = "")
        { 
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                string name = String.Empty;
                name = db.Achievements.Where(w => w.LevelCode.Equals(levelCode)).FirstOrDefault().Name;
                return name;
            }
        }
        public List<GioiHanGoiActive> getAllGioiHanGoiActive()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.GioiHanGoiActives.ToList();
            }
        }
        public BankList[] getListBank()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = DuAnDaCapEntities.initDuAnDaCapEntities(connection))
            {
                return db.BankLists.Where(w=>w.Status != null && w.Status != false).ToArray();
            }
        }

    }

    public class HistoryProfitPackDetail
    {
        public string Date { get; set; }
        public string Profit { get; set; }
    }
    public class CustomOrder
    {
        public int ID { get; set; }
        public string STT { get; set; }
        public string ID_OrDer { get; set; }
        public string HoTen { get; set; }
        public double? Amount { get; set; }
        public int? PV { get; set; }
        public DateTime? CreateDate { get; set; }
        public string Package_Name { get; set; }
        public bool? NewAction { get; set; }
        public int? Numpackage { get; set; }

    }

    public class PayMentUser
    {
        public string UserName { get; set; }
        public int UserId { get; set; }
        public string HoTen { get; set; }
        public DateTime? NgaySinh { get; set; }
        public string SoTK { get; set; }
        public string NganHang { get; set; }
        public int? Thang { get; set; }
        public int? Nam { get; set; }
        public bool? NangDong { get; set; }
        public double? SoTien { get; set; }
        public double? ThanhTien { get; set; }
        public string SOCMND { get; set; }

    }
    public class OrderViewModel
    {
        public int UserId { get; set; }

        public string OrderId { get; set; }

        public string UserName { get; set; }

        public double? Amount { get; set; }

        public DateTime? Date { get; set; }

        public string HoTen { get; set; }

        public int Stt { get; set; }
    }

    public class ManagerPack
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public double? Percent { get; set; }
        public double Amount { get; set; }
        public string CreateDate { get; set; }
    }
    public class ProvideOrderView
    {
        public int Id { get; set; }
        public int UserIdGive { get; set; }
        public string UserGive { get; set; }
        public int UserIdGet { get; set; }
        public string UserGet { get; set; }
        public int Status { get; set; }
        public int OrderId { get; set; }
        public string Id_Order { get; set; }
        public double Amount { get; set; }
        public string RoomCode { get; set; }
        public string PhoneGet { get; set; }
        public string EmailGet { get; set; }
    }
    public class ProvideHelp
    {
        public DateTime CreateDate{get;set;}
        public double Amount{get;set;}
        public int UserId{get;set;}
        public double Extant{get;set;}
        public double Delivered{get;set;}
        public int Status{get;set;}
        public DateTime GH_Date { get; set; }
    }
}

    

